﻿using System.AutoUpdate.Core;
using System.AutoUpdate.Core.Operations;
using System.AutoUpdate.Library;
using System.AutoUpdate.Managers;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;

namespace System.AutoUpdate.Operations
{
    /// <summary>
    /// Checks for updates in background thread
    /// </summary>
    public class CheckOperation : BackgroundOperation
    {
        public override bool StartOperation (UpdateInfo info)
        {
            Info = info ?? new UpdateInfo ();

            if (SourceManager.Instance.Sources.Count > 0)
            {
                OperationEvent(Core.OperationEvent.Started, this, new OperationEventArgs ());

                Run ();

                return true;
            }

            return false;
        }

        protected override void WorkerOnDoWork (object sender, DoWorkEventArgs doWorkEventArgs)
        {
            System.Threading.Thread.Sleep (2000);

            //
            // Separate Thread for each update source
            //

            Parallel.ForEach (SourceManager.Instance.Sources, source =>
            {
                List <UpdateVersionInfo> versions = source.GetVersions ();

                lock (Info)
                {
                    foreach (UpdateVersionInfo version in versions)
                    {
                        Info.AvailableVersions.Add (version);
                    }
                }
            });
        }
    }
}
